﻿Imports System.IO
Imports System.Text
Imports System.Threading

Namespace Diagnostics.Profiler.Recorder
    Public Class FileRecorder
        Inherits BaseRecorder

        Private Const _dbPath As String = "profiler.db"
        Private _records As New Dictionary(Of String, ProfilerRecord)
        Private _isWaiting As Boolean = False

        Public Overrides Sub Record(ByVal key As String, ByVal callSpan As TimeSpan)
            SyncLock _records
                If Not _records.ContainsKey(key) Then
                    _records(key) = New ProfilerRecord(callSpan)
                Else
                    _records(key).Add(callSpan)
                End If
                If Not _isWaiting Then
                    _isWaiting = True
                    Dim t As New Thread(AddressOf FlushRecords)
                    t.Start()
                End If
            End SyncLock
        End Sub

        Private Sub FlushRecords()
            Thread.Sleep(1000)
            SyncLock _records
                Dim builder As New StringBuilder
                For Each kv As KeyValuePair(Of String, ProfilerRecord) In _records
                    builder.Append(kv.Key).Append(vbTab)
                    builder.Append(kv.Value.Count).Append(vbTab)
                    builder.AppendLine(kv.Value.CallSpan.ToString())
                Next
                Using s As New StreamWriter(Path.Combine(Directory.GetCurrentDirectory, _dbPath), False)
                    s.WriteLine(builder.ToString())
                End Using
                _isWaiting = False
            End SyncLock
        End Sub
    End Class
End Namespace
